<!-- src/views/UserRoleAssignment.vue -->
<template>
    <div class="container">
      <el-button type="primary" @click="goBack">返回用户列表</el-button>
      
      <el-divider>当前用户：{{ currentUser.loginid }}</el-divider>
      
      <div class="assignment-container">
        <div class="current-roles">
          <h3>已分配角色</h3>
          <el-table :data="assignedRoles">
            <el-table-column prop="roleName" label="角色名称"/>
            <el-table-column label="操作">
              <template #default="{row}">
                <el-button size="small" type="danger" 
                  @click="removeRole(row.roleId)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
  
        <div class="available-roles">
          <h3>可用角色</h3>
          <el-table :data="allRoles">
            <el-table-column prop="roleName" label="角色名称"/>
            <el-table-column label="操作">
              <template #default="{row}">
                <el-button size="small" type="primary" 
                  @click="assignRole(row.roleId)">分配</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </template>
 <script setup>
 import { ref, onMounted } from 'vue'
 import { useRoute, useRouter } from 'vue-router'
 import { getUserRoles, addUserRole, removeUserRole } from '@/api/userRoleApi'
 import { getUserById } from '@/api/userApi'
 import { getAllRoles } from '@/api/roleApi' // 添加这行


 
 const route = useRoute()
 const router = useRouter()
 const userId = parseInt(route.params.userId)
 
 const currentUser = ref({})
 const assignedRoles = ref([]) // 格式: { roleId: number, roleName: string }[]
 const allRoles = ref([])      // 格式: { roleId: number, roleName: string }[]
 
 onMounted(async () => {
   await loadData()
 })
 
 const loadData = async () => {
  try {
    // 1. 获取用户基本信息
    const userRes = await getUserById(userId)
    currentUser.value = userRes.data

    // 2. 获取所有角色（使用新接口）
    const rolesRes = await getAllRoles() // 修改这里
    const roleMap = new Map(rolesRes.data.map(r => [r.roleId, r.roleName]))

    // 3. 获取用户已分配角色
    const userRolesRes = await getUserRoles(userId)
    
    // 4. 映射角色名称
    assignedRoles.value = userRolesRes.data.map(ur => ({
      roleId: ur.roleId,
      roleName: roleMap.get(ur.roleId) || '未知角色'
    }))

    // 5. 过滤未分配角色
    allRoles.value = rolesRes.data.filter(r => 
      !userRolesRes.data.some(ur => ur.roleId === r.roleId)
    )
  } catch (error) {
    console.error('数据加载失败', error)
  }
}
 
 // 分配角色方法（保持原逻辑）
 const assignRole = async (roleId) => {
   await addUserRole({ userId, roleId })
   await loadData()
 }
 
 // 移除角色方法（保持原逻辑）
 const removeRole = async (roleId) => {
   await removeUserRole(userId, roleId)
   await loadData()
 }
 
 // 返回用户列表（保持原逻辑）
 const goBack = () => {
   router.push({ name: 'user-list' })
 }
 </script>
  
  <style scoped>
  .assignment-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-top: 20px;
  }
  
  .current-roles, .available-roles {
    border: 1px solid #ebeef5;
    padding: 15px;
    border-radius: 4px;
  }
  
  h3 {
    margin: 0 0 15px 0;
    color: #606266;
  }
  </style>